package RPCClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.rabbit.chat.core.IRabbitChat;
import com.rabbit.chat.core.RabbitChat;

public class ChatClient implements Runnable{

	private IRabbitChat chatClientManager;

	public ChatClient(IRabbitChat manager){
		chatClientManager = manager;
	}

	private void startChat(){
		try{

			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String messageToSend = null;
			while(true){
				messageToSend = br.readLine();
				if(messageToSend.equals("close"))
					break;
				chatClientManager.SendMessage(messageToSend);
			}
		}
		catch  (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (chatClientManager!= null) {
				try {
					chatClientManager.close();
				}
				catch (Exception ignore) {}
			}
		}
	}

	public void run() {
		startChat();
	}


	public static void main(String[] argv) throws Exception {
		IRabbitChat c = null;
		if(argv.length==2)
			c= new RabbitChat(argv[0], argv[1]){
			@Override
			public void OnMessageReceive(String sender, String message) {
				System.out.println("[x] from " + sender + ": "+ message + "");
			}
			
			@Override
			public void OnLastMessageSent() {
				// TODO Auto-generated method stub
				super.OnLastMessageSent();
			}
			
			@Override
			public void OnError(Exception e) {
				// TODO Auto-generated method stub
				super.OnError(e);
			}
		};
		else
			c= new RabbitChat(argv[0]){
			@Override
			public void OnMessageReceive(String sender, String message) {
				System.out.println("[x] from " + sender + ": "+ message + "");
			}
			
			@Override
			public void OnLastMessageSent() {
				// TODO Auto-generated method stub
				super.OnLastMessageSent();
			}
			
			@Override
			public void OnError(Exception e) {
				// TODO Auto-generated method stub
				super.OnError(e);
			}
		};
		
		new Thread(new ChatClient(
				c.Initialize())).start();
		System.out.println("Client " +argv[0]+" Created");   
	}
}